package com.grouponmall.service;

import java.util.Date;
import java.util.List;

import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.grouponmall.model.Deal;

/**
 * @author xueqiang.mi
 * @since 2010-5-8
 */
public abstract class BaseRetrieveService {

  private DealServiceImpl dealService = new DealServiceImpl();

  public void setDealService(DealServiceImpl dealService) {
    this.dealService = dealService;
  }

  public void retrieve() throws Exception {
    NodeList nodeList = getExpectedLinks(getURL());
    if (nodeList == null) {
      return;
    }
    int end = nodeList.size();
    for (int i = 0; i < end; i++) {
      LinkTag linkTag = (LinkTag) nodeList.elementAt(i);
      List<Deal> deals = extract(linkTag.getLink());
      if (deals == null || deals.isEmpty()) {
        return;
      }
      for (Deal deal : deals) {
        if (deal != null && deal.getCity() != null && deal.getTitle() != null) {
          dealService.delDeal(deal.getCity(), deal.getTitle());
          deal.setCreatedDate(new Date());
          dealService.addDeal(deal);
        }
      }
    }
    return;
  }

  public abstract String getURL();

  public abstract List<Deal> extract(String link) throws Exception;

  public abstract NodeList getExpectedLinks(String link) throws ParserException;
}
